package a04_字符串;

import java.util.Arrays;

/**
 * <p>
 * a04_反转字符串中的单词
 * </p>
 *
 * @author flyduck
 * @since 2024-07-10
 */
public class a04_反转字符串中的单词 {
    public static void main(String[] args) {
        System.out.println(reverseWords("a good   example"));
    }

    public static String reverseWords(String s) {
        char[] oldChars = s.toCharArray();
        //1.去除首尾以及中间多余空格
        char[] newChars = removeExtraSpaces(oldChars);
        //字符串整个翻转
        reverse(newChars,0,newChars.length-1);
        //翻转单词
        reverseEachWord(newChars);
        return new String(newChars);
    }

    private static char[] removeExtraSpaces(char[] oldChars) {
        int slowIndex = 0;//要赋值的索引
        for (int fastIndex = 0; fastIndex < oldChars.length; fastIndex++) {
            if (oldChars[fastIndex] != ' ') {
                //除了第一个单词，其他单词都要加空格
                if(slowIndex != 0){
                    oldChars[slowIndex] = ' ';
                    slowIndex++;
                }

                while (fastIndex < oldChars.length && oldChars[fastIndex] != ' '){//如果便利的元素不是空格，给slowIndex赋值
                    //如果是单词的第一个，应该给前面加一个空格，怎么判断是单词的第一个
                    oldChars[slowIndex] = oldChars[fastIndex];
                    slowIndex++;
                    fastIndex++;
                }
            }

        }

        return Arrays.copyOfRange(oldChars, 0, slowIndex);
    }

    private static void reverseEachWord(char[] chars) {
        int leftIndex = 0;
        for (int rightIndex = 0; rightIndex <= chars.length; rightIndex++) {
            if(rightIndex == chars.length || chars[rightIndex] == ' '){
                reverse(chars, leftIndex, rightIndex - 1);
                leftIndex = rightIndex + 1;
            }
        }
    }

    public static void reverse(char[] chars,int leftIndex,int rightIndex){
        while (leftIndex < rightIndex) {
            char temp = chars[leftIndex];
            chars[leftIndex] = chars[rightIndex];
            chars[rightIndex] = temp;
            leftIndex++;
            rightIndex--;
        }
    }
}
